<!-- 商品发布 - 基础设置 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="150px">
    <el-form-item label="是否虚拟商品" prop="virtualProduct">
      <el-radio-group
        disabled
        @change="changeVirtualProduct"
        v-model="formData.virtualProduct"
        class="w-80"
      >
        <el-radio :label="true" class="radio">是</el-radio>
        <el-radio :label="false">否</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="上线渠道" prop="salesChannel">
      <el-select v-model="formData.salesChannel" class="w-80">
        <el-option v-for="item in SaleChannelOptionList" :key="item.value" :label="item.text" :value="item.value"/>
      </el-select>
    </el-form-item>
    <el-form-item label="商品名称" prop="name">
      <el-input
        v-model="formData.name"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="64"
        placeholder="请输入商品名称"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="商品类型" prop="productType">
      <el-select v-model="formData.productType" class="w-80">
        <el-option v-for="item in ProductTypeOptionList" :key="item.value" :label="item.text" :value="item.value"/>
      </el-select>
    </el-form-item>
    <el-form-item label="商品分类" prop="categoryId">
      <el-cascader
        v-model="formData.categoryId"
        :options="categoryList"
        :props="defaultProps"
        class="w-80"
        clearable
        filterable
        placeholder="请选择商品分类"
      />
    </el-form-item>
    <el-form-item label="充值方式" prop="rechargeMethod">
      <el-select placeholder="请选择充值方式" v-model="formData.rechargeMethod" class="w-80">
        <el-option
          v-for="item in RechargeMethodTypeOptionList"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
<!--    <el-form-item label="商品品牌" prop="brandId">-->
<!--      <el-select v-model="formData.brandId" class="w-80" placeholder="请选择商品品牌">-->
<!--        <el-option-->
<!--          v-for="item in brandList"-->
<!--          :key="item.id"-->
<!--          :label="item.name"-->
<!--          :value="item.id as number"-->
<!--        />-->
<!--      </el-select>-->
<!--    </el-form-item>-->
    <el-form-item label="商品排序" prop="sort" style="margin-right:16px;">
      <el-input-number v-model="formData.sort" :min="1" />
    </el-form-item>
    <el-form-item label="商品关键字" prop="keyword">
      <el-input v-model="formData.keyword" class="w-80!" placeholder="请输入商品关键字" />
    </el-form-item>
    <el-form-item label="售价币种" prop="currencyCode">
      <el-select @change="changeCurrencyCode" v-model="formData.currencyCode" class="w-80" placeholder="请选择售价币种">
        <el-option
          v-for="item in currencyList"
          :key="item.currencyCode"
          :label="item.currencyName"
          :value="item.currencyCode"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="固定面值折扣率(%)" prop="discountRate">
        <el-input-number v-model="formData.discountRate" :min="0.01" :step="0.01" />
        (折扣输入小于100,溢价输入大于100。)
    </el-form-item>
<!--    <el-form-item label="商品简介" prop="introduction">-->
<!--      <el-input-->
<!--        v-model="formData.introduction"-->
<!--        :autosize="{ minRows: 5, maxRows: 10 }"-->
<!--        :clearable="true"-->
<!--        :show-word-limit="true"-->
<!--        class="w-80!"-->
<!--        maxlength="512"-->
<!--        placeholder="请输入商品简介"-->
<!--        type="textarea"-->
<!--      />-->
<!--    </el-form-item>-->
<!--    <el-form-item label="商品地区" prop="region">-->
<!--        <el-input v-model="formData.region" class="w-80!" placeholder="请输入商品地区" />-->
<!--    </el-form-item>-->
    <el-form-item label="商品封面图" prop="picUrl">
      <UploadImg v-model="formData.picUrl" :disabled="isDetail" height="80px" />
      （推荐 256*256 图片分辨率）
    </el-form-item>
<!--    <el-form-item label="商品轮播图" prop="sliderPicUrls">-->
<!--      <UploadImgs v-model="formData.sliderPicUrls" :disabled="isDetail" />-->
<!--    </el-form-item>-->
    <el-form-item label="商品详情（中文）" prop="description">
      <Editor :readonly="isDetail" v-model:modelValue="formData.description" />
    </el-form-item>
    <el-form-item label="商品详情（英文）" prop="description">
      <Editor :readonly="isDetail" v-model:modelValue="formData.descriptionEn" />
    </el-form-item>
    <el-form>
      <el-form-item style="float: right">
        <el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
          保存
        </el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>
    </el-form>
  </el-form>
</template>
<script lang="ts" setup>
import {EnumSaleChannelType, SaleChannelOptionList} from '@/config/spu';
const { t } = useI18n() // 国际化
import { PropType } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'
import type { Spu } from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { CategoryVO } from '@/api/mall/product/category'
import * as ProductBrandApi from '@/api/mall/product/brand'
import {ExchangeRateApi} from '@/api/mall/currency/rate/index';
import { BrandVO } from '@/api/mall/product/brand'
import {
  EnumProductType,
  EnumRechargeMethodType, EnumTradeDeliveryType, EnumUserCustomInputType,
  ProductTypeOptionList,
  RechargeMethodTypeOptionList
} from "@/config/spu";
import {Editor} from "@/components/Editor";
import {useTagsViewStore} from "@/store/modules/tagsView";
import {cloneDeep} from "lodash-es";
import * as ProductSpuApi from "@/api/mall/product/spu";
const { push, currentRoute } = useRouter() // 路由
const { delView } = useTagsViewStore() // 视图操作

defineOptions({ name: 'ProductSpuInfoForm' })
const props = defineProps({
  id: propTypes.number.def(undefined),
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const message = useMessage() // 消息弹窗
const formLoading = ref(false);
const formRef = ref() // 表单 Ref
const currencyList = ref([]);
const formData = ref<Spu>({
  discountRate: 100,
  salesChannel: EnumSaleChannelType.ALL,
  virtualProduct: true, // 是否虚拟商品
  rechargeMethod: EnumRechargeMethodType.CARD_CODE, // 充值方式
  region: "", // 商品区域
  productType: EnumProductType.GIFT_CARD, // 商品类型
  name: '', // 商品名称
  categoryId: undefined, // 商品分类
  keyword: '', // 关键字
  currencyCode: undefined,
  picUrl: '', // 商品封面图
  sliderPicUrls: [], // 商品轮播图
  introduction: '', // 商品简介
  brandId: undefined, // 商品品牌,
  description: "", // 商品详情
  descriptionEn: "", // 商品详情英文
  sort: 0, // 商品排序
  giveIntegral: 0, // 赠送积分
  virtualSalesCount: 0, // 虚拟销量
  specType: true, // 商品规格
  subCommissionType: false, // 分销类型
})
const rules = reactive({
  virtualProduct: [required],
  salesChannel: [required],
  discountRate: [required],
  productType: [required],
  rechargeMethod: [required],
  currencyCode: [required],
  region: [],
  name: [required],
  categoryId: [required],
  keyword: [required],
  introduction: [],
  picUrl: [required],
  sliderPicUrls: [],
  // brandId: [required],
  description: [required],
  descriptionEn: [required],
  sort: [required],
})

watch(
  () => formData.value.description,
  (newValue) => {
    if ('<p><br></p>' === newValue) {
      formData.value.description = ''
    }
  },
  {
    deep: true,
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['changeVirtualProduct'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
  } catch (e) {
    formLoading.value = false;
    message.error('必填字段项不完整，请输入后提交')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

function changeVirtualProduct() {
  emit("changeVirtualProduct", formData.value.virtualProduct)
}

/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'ProductSpu' })
}

const getDetail = async ()=> {
  if(props.id) {
    const res = (await ProductSpuApi.getSpu(props.id)) as ProductSpuApi.Spu

    formData.value = res
  }
}

const changeCurrencyCode = async ()=> {
  if(formData.value.skus && formData.value.skus.length) {
    message.alert("系统检测到已经添加过商品sku，如有关联CDK，请确认货币类型是否一致");
  }
}

const submitForm = async ()=> {
  formLoading.value = true

  // 校验表单数据
  await validate();
  if(formData.value.descriptionEn === "<p><br></p>") {
    formLoading.value = false;
    return message.warning("请输入商品详情（英文）");
  }

  let deepCopyFormData = cloneDeep(unref(formData.value)) as ProductSpuApi.Spu;
  // 处理轮播图列表
  const newSliderPicUrls: any[] = []
  deepCopyFormData.sliderPicUrls!.forEach((item: any) => {
    // 如果是前端选的图
    typeof item === 'object' ? newSliderPicUrls.push(item.url) : newSliderPicUrls.push(item)
  })
  deepCopyFormData.sliderPicUrls = newSliderPicUrls;
  switch (formData.value.rechargeMethod) {
    case EnumRechargeMethodType.DIRECT_RECHARGE:
      deepCopyFormData.customUserInput = [EnumUserCustomInputType.RECHARGE_ACCOUNT];
      break;
    case EnumRechargeMethodType.CARD_CODE:
      deepCopyFormData.customUserInput = [EnumUserCustomInputType.RECEIVE_EMAIL];
      break;
  }
  deepCopyFormData.deliveryTypes = [EnumTradeDeliveryType.NO_DELIVERY_NEEDED]; // 配送方式
  deepCopyFormData.deliveryTemplateId = undefined; // 运费模版

  // if(!deepCopyFormData.brandId && brandList.value) {
  //   deepCopyFormData.brandId = brandList.value[0].id;
  // }
  delete deepCopyFormData.skus;
  const id = props.id as unknown as number
  try {
    if (!id) {
      let resId = await ProductSpuApi.createSpu(deepCopyFormData);
      message.success(t('common.createSuccess'))
      close()
      nextTick(()=> {
        push({ name: 'ProductSpuEdit', params: { id: resId } })
      })
    } else {
      await ProductSpuApi.updateSpu(deepCopyFormData)
      message.success(t('common.updateSuccess'))
      close()
    }
  } catch (e) {
    formLoading.value = false;
  }
}

/** 初始化 */
const brandList = ref<BrandVO[]>([]) // 商品品牌列表
const categoryList = ref<CategoryVO[]>([]) // 商品分类树
onMounted(async () => {
  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({})
  categoryList.value = handleTree(data, 'id')
  // 获取商品品牌列表
  brandList.value = await ProductBrandApi.getSimpleBrandList()

  let currencyRes = await ExchangeRateApi.getExchangeRatePage({
    pageNo: 1,
    pageSize: 100
  });
  currencyList.value = currencyRes.list;

  await getDetail();
})
</script>
